package com.gitee.cashzhang27.test.boot.keycloak.util;

import java.util.List;
import java.util.Map;
import org.keycloak.AuthorizationContext;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessToken.Access;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.idm.authorization.Permission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
 * Identity.
 *
 * @author Cash Zhang
 * @version v1.0 2020/08/07 14:31
 * @since v1.0
 */
public class Identity {

  public static boolean hasResourcePermission(String name) {
    return getAuthorizationContext().hasResourcePermission(name);
  }

  public static String getUserId() {
    return getAccessToken().getId();
  }

  public static String getPreferredUsername() {
    return getAccessToken().getPreferredUsername();
  }

  public static String getRealms() {
    return getKeycloakSecurityContext().getRealm();
  }

  public static Access getRealmAccess() {
    return getAccessToken().getRealmAccess();
  }

  public static Map<String, Access> getResourceAccess() {
    return getAccessToken().getResourceAccess();
  }

  public static Access getResourceAccessByResource(String resource) {
    return getAccessToken().getResourceAccess(resource);
  }

  public static IDToken getIdToken() {
    return getKeycloakSecurityContext().getIdToken();
  }

  public static AccessToken getAccessToken() {
    return getKeycloakSecurityContext().getToken();
  }

  public static List<Permission> getPermissions() {
    return getAuthorizationContext().getPermissions();
  }

  private static AuthorizationContext getAuthorizationContext() {
    return getKeycloakSecurityContext().getAuthorizationContext();
  }

  private static KeycloakSecurityContext getKeycloakSecurityContext() {
    return getKeycloakAuthenticationToken().getAccount().getKeycloakSecurityContext();
  }

  private static KeycloakAuthenticationToken getKeycloakAuthenticationToken() {
    return (KeycloakAuthenticationToken) getAuthentication();
  }

  public static Authentication getAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }
}
